import { type Table } from '@tanstack/react-table'
import { Button } from '@/components/ui/button'
import { ConfirmDialog } from '@/components/confirm-dialog'
import { IconAlertTriangle } from '@tabler/icons-react'
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
import { IconTrash } from '@tabler/icons-react'

import { useState } from 'react'
import { toast } from 'sonner'
import { convertTreeSelectedToString } from '@/utils/tree-util'
import { useRouter } from '@tanstack/react-router'
import { useRuleDel } from '@/api/rules'

interface DataTableToolbarProps<TData> {
  table: Table<TData>
}

export function DataTableToolbar<TData>({
  table,
}: DataTableToolbarProps<TData>) {
  const selectedItems = convertTreeSelectedToString(table.getState().rowSelection)
  const router = useRouter()
  const [open, setOpen] = useState(false)
  const ruleDel = useRuleDel()
  const handleDelete = () => {
    ruleDel.mutate({ id: selectedItems.split(',') }, {
      onSuccess: () => {
        setOpen(false)
        toast.success('Deleted successfully!')
        router.invalidate();
      },
    })
  }
  const onOpenChange = () => {
    setOpen(!open)
  }
  return (
    <div className='flex items-center justify-between'>
      <div className='flex flex-1 flex-col-reverse items-start gap-y-2 sm:flex-row sm:items-center sm:space-x-2'>

        <Button
          variant='outline'
          onClick={() => setOpen(true)}
          className='h-8 px-2 lg:px-3 text-red-500!'
        >
          Delete
          <IconTrash size={16} />
        </Button>
        <ConfirmDialog
          open={open}
          onOpenChange={onOpenChange}
          handleConfirm={handleDelete}
          title={
            <span className='text-destructive'>
              <IconAlertTriangle
                className='stroke-destructive mr-1 inline-block'
                size={18}
              />{' '}
              Delete Role
            </span>
          }
          desc={
            <div className='space-y-4'>
              <p className='mb-2'>
                Are you sure you want to delete
                <span className='font-bold break-all'>{selectedItems}</span>?
                <br />
                from the system. This cannot be undone.
              </p>
              <Alert variant='destructive'>
                <AlertTitle>Warning!</AlertTitle>
                <AlertDescription>
                  Please be carefull, this operation can not be rolled back.
                </AlertDescription>
              </Alert>
            </div>
          }
          confirmText='Delete'
          destructive
        />

      </div>
    </div>
  )
}
